package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Util.CurrentUserContextHolders;
import com.qk.common.enums.AOPEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author: zyx
 * @created: 2025-10-17-18:00
 * @description:
 */
@Aspect
@Component
@Slf4j
public class LogRecordAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.qk.management.aop.anno.LogAnno)")
    public Object around(ProceedingJoinPoint pjp) {

        long start = System.currentTimeMillis();
        Object returnValue = null;
        try {
            returnValue = pjp.proceed();
        } catch (Throwable e) {
            CommonException.throwCommonException(AOPEnum.OPERATION_FAILED);
        }
        long end = System.currentTimeMillis();
        OperateLog operateLog = OperateLog.builder()
                .costTime(end - start)
                .className(pjp.getTarget().getClass().getName())
                .operateUserId(CurrentUserContextHolders.get())
                .methodName(pjp.getSignature().getName())
                .methodParams(JSONUtil.toJsonStr(pjp.getArgs()))
                .returnValue(JSONUtil.toJsonStr(returnValue))
                .operateTime(LocalDateTime.now())
                .build();
        try {
            operateLogMapper.insert(operateLog);
        } catch (Exception e) {
            log.error("记录操作日志异常", e);
        }


        return returnValue;
    }
}
